<template>
  <div class="container">
    <div style="height:36px;"></div>
    <div style="padding:10px;box-sizing: border-box;">
      <header>
        <t-button @click="back" variant="outline">
          <template #icon><ArrowLeftIcon /></template>
          返回
        </t-button>
      </header>
      <t-card style="margin-top: 10px;">
        <div style="height:64px;">
          <t-space>
            <t-upload
                action=""
                :auto-upload="false"
                :multiple="false"
                :format-response="formatResponse"
                :on-change="handleFileChange"
                accept=".xlsx, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            >
              <t-button variant="outline">
                <template #icon><cloud-upload-icon /></template>
                上传Excel</t-button>
            </t-upload>
            <t-button theme="primary" @click="makeCMD">

              <template #icon><WorkIcon /></template>
              生成命令</t-button>
            <t-button theme="danger" @click="clearAll">

              <template #icon><ClearIcon /></template>
              清空</t-button>
            <t-button theme="success" @click="downloadTemplate">
              <template #icon><cloud-download-icon /></template>
              模板</t-button>
          </t-space>
        </div>
        <div>
          <div>
            <t-textarea v-model:value="parseStr" :autosize="{ minRows: 3, maxRows: 5 }"></t-textarea>
          </div>
          <div style="margin-top: 20px;">
            <t-space>
              <t-button theme="warning" @click="Validate" :loading="loading">校验</t-button>
              <t-tooltip content="最近一次上传">
                <t-button @click="getLatest">
                  <template #icon><RollbackIcon /></template>
                  加载</t-button>
              </t-tooltip>
            </t-space>

            <t-table
                :stripe="true"
                :max-height="500"
                style="margin-top: 10px;" row-key="id" size="small" bordered :data="result" :columns="[
              { colKey: 'ID', title: '序号',width:80},
              { colKey: 'url', title: '链接'},
              { colKey: 'batch_no', title: '批次'},
              ]">
            </t-table>
          </div>
        </div>
        <div>
          <t-dialog
              v-model:visible="visible"
              width="800"
              header="复制剁手命令"
              destroy-on-close
              @confirm="visible=false"
          >
            <template #body>
              {{cmd}}
            </template>
          </t-dialog>
        </div>
        <t-divider>校验</t-divider>
        <t-row :gutter="16">
          <t-col :span="4" v-for="(v,ind) in valiStr" :key="ind">
            <span style="font-size: 10px;word-wrap: break-word">{{v}}</span>
          </t-col>
        </t-row>
      </t-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import { EventsEmit, EventsOn } from "../../wailsjs/runtime/runtime";

import { DownloadTemplate, SaveFileDialoging,SaveFile,LastTime,GenCommand,ValidRequst } from "../../wailsjs/go/main/App";
import {
  RollbackIcon,
  ArrowLeftIcon,
  CloudUploadIcon,
  WorkIcon,
  CloudDownloadIcon,
  ClearIcon
} from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import router from "../router/index.js";
const result =ref([])


const formatResponse=()=>{
  return {
    name: '默认文件',
    url: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    status: 'success',
    size: 1024,
    uploadTime: '2022-09-25',
  }
}

const parseStr = ref("")
const handleFileChange = async (file) => {
  if (!file || !file[0].raw) {
    console.error('未选择文件或文件对象无效');
    return;
  }

  try {
    // 从 TDesign 的 file 对象中提取原生 File 对象
    const rawFile = file[0].raw;

    // 将文件转换为 ArrayBuffer
    const arrayBuffer = await rawFile.arrayBuffer();
    const base64String = arrayBufferToBase64(arrayBuffer);
    // 发送二进制数据到后端
    EventsEmit("uploadFile", base64String);

    // 监听后端返回的结果
    EventsOn("fileProcessed", (res) => {
      parseStr.value=res;
    });
  } catch (error) {
    console.error('文件解析失败:', error);
    parseStr.value = '文件解析失败';
  }
};

// 将 ArrayBuffer 转换为 Base64 字符串
const arrayBufferToBase64 = (buffer) => {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
};
const back = ()=>{
  router.go(-1);
}

const downloadTemplate = async () => {

  try {
    // 调用后端方法
    const response = await DownloadTemplate();

    // 打开文件保存对话框
    const filePath = await SaveFileDialoging({
      defaultFilename: response.FileName, // 默认文件名
      filters: [
        {
          name: "Excel Files",
          pattern: "*.xlsx", // 文件类型过滤器
        },
      ],
    });

    if (filePath) {
      // 将文件数据保存到指定路径
      await SaveFile(filePath, response.Data);
      alert("文件保存成功！");
    } else {
      alert("文件保存取消。");
    }
  } catch (error) {
    console.error("下载模板失败:", error);
  }
};

// 上一次，历史
const getLatest=async ()=>{
  result.value = await LastTime()
}
const cmd =ref("")
const makeCMD = async ()=>{
  if(result.value.length==0){
    return MessagePlugin.error("无效数据，请先加载");
  }
  const da = await GenCommand()
  cmd.value=da
  console.log("da",da)
  if (navigator.clipboard) {
    navigator.clipboard
        .writeText(cmd.value)
        .then(() => {
          console.log("文本已复制到剪贴板:", cmd.value);

          MessagePlugin.success("生成成功，已拷贝到剪贴板");
          visible.value=true
        })
        .catch((error) => {
          console.error("复制失败:", error);
          fallbackCopyToClipboard(cmd.value); // 降级方案
        });
  } else {
    fallbackCopyToClipboard(cmd.value); // 降级方案
  }
}

const visible=ref(false)


const fallbackCopyToClipboard = (text) => {
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position = "fixed"; // 避免滚动
  document.body.appendChild(textarea);
  textarea.select();

  try {
    const success = document.execCommand("copy");
    if (success) {
      console.log("文本已复制到剪贴板:", text);
      MessagePlugin.success("复制成功")
    } else {
      console.error("复制失败: execCommand 不支持");
      MessagePlugin.error("复制失败")

    }
  } catch (error) {
    MessagePlugin.error("复制失败")
  } finally {
    document.body.removeChild(textarea);
  }
};
const clearAll= ()=>{
  valiStr.value=[];
  cmd.value="";
  parseStr.value="";
  result.value=[];
}
const valiStr=ref([])
const loading = ref(false)

//校验
const  Validate = async ()=>{
  if(result.value.length==0){
    return MessagePlugin.error("没有数据")
  }
  loading.value=true
  let bt = result.value[0].batch_no
  valiStr.value = await ValidRequst(bt)
  result.value=[];
  loading.value=false
}
</script>

<style scoped>
.container{
  background-image: linear-gradient(25deg, #3927a2, #7d56a7, #b088aa, #dfbdab);
  min-height:768px;
}

</style>